import { saveRecord, treeParticipateOrganization } from '@/services/api/api-publicity-record';
import { treeSource } from '@/services/api/api-publicity-source';
import { FileOutlined, FolderOutlined, PlusOutlined, TagOutlined } from '@ant-design/icons';
import ProForm, {
  DrawerForm,
  ProFormCascader,
  ProFormDatePicker,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import ProList from '@ant-design/pro-list';
import {
  Avatar,
  Button,
  Divider,
  Empty,
  Select,
  Space,
  Spin,
  Tag,
  Typography,
  message,
} from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddAttachmentFile from './attachment/AddAttachmentFile';
import AddAttachmentLink from './attachment/AddAttachmentLink';
import AddAttachmentSignal from './attachment/AddAttachmentSignal';

interface AddRecordProps {
  onRefurbish: () => void;
}

const AddRecord: React.FC<AddRecordProps> = ({ onRefurbish }) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  /**
   * 初始化Cascader数据
   */

  const [dataSource, setDataSourceState] = useState<any>();

  /**
   * 选择 Cascader数据 来源
   */
  const [selectSource, setSelectSourceState] = useState<any>();

  /**
   * 附件数据
   */
  const [dataAttachment, setDataAttachmentState] = useState<PublicityRecordBo.Attachment[]>([]);

  /**
   * 分数符号
   */
  const [scoreSymbols, setScoreSymbolsState] = useState('add');
  useEffect(() => {}, [selectSource]);

  const selectBefore = (
    <Select defaultValue={scoreSymbols === '' ? undefined : scoreSymbols} key={scoreSymbols}>
      <Option value="add">+</Option>
      <Option value="minus">-</Option>
    </Select>
  );
  /**
   * 预备Cascader结构数据
   * @param data
   */
  function readyCascaderData(data: PublicitySourceData.Source[]): any {
    const cascaderData = new Array();
    if (data) {
      data.forEach((val) => {
        cascaderData.push({
          // label: `${val.name}${val.score != null ? `（${val.score}）` : ''}`,
          label: (
            <>
              <span
                style={{
                  color:
                    val.score === null
                      ? ''
                      : Number(val.score) > 0
                      ? ''
                      : Number(val.score) === 0
                      ? '#FFD591'
                      : 'red',
                }}
              >
                {val.name}
              </span>
              <span
                style={{
                  color: Number(val.score) > 0 ? '' : Number(val.score) === 0 ? '#FFD591' : 'red',
                }}
              >
                {val.score !== null ? '(' + val.score + ')' : ''}
              </span>
            </>
          ),
          value: val.id,
          describes: val.describes,
          score: val.score,
          children: readyCascaderData(val.children as PublicitySourceData.Source[]),
        });
      });
    }
    return cascaderData;
  }

  /**
   * 加载来源详情
   * @param key
   */
  const loadSourceData = async () => {
    try {
      const response = await treeSource();
      if (response.code === 0) {
        const CascaderData = readyCascaderData(response.data);
        setDataSourceState(CascaderData);
      }
    } catch (error) {}
  };

  function disabledDate(current: any) {
    // Can not select days before today and today
    return current && current > moment().endOf('day');
  }

  /**
   * 初始化树形数据
   */
  const [treeOrganizationData, setTreeOrganizationDataState] = useState<DataNode[]>();
  /**
   * 树形列表选择数据
   */
  const [checkedOrganizations, setCheckedOrganizationsState] = useState<any[]>([]);

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          title: val.name,
          key: val.id,
          item: val,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
          icon: val.isFolder === 0 ? <TagOutlined /> : <FolderOutlined />,
        });
      });
    }
    return treeData;
  }

  /**
   * 加载组织详情
   * @param key
   */
  const loadOrganizationData = async () => {
    try {
      const response = await treeParticipateOrganization();
      if (response.code === 0) {
        const treeData = new Array<DataNode>();
        treeData.push({
          title: '融媒通',
          key: '0',
          item: { id: '0', name: '融媒通' },
          children: readyTreeData(response.data),
        });
        setTreeOrganizationDataState(treeData);
      }
    } catch (error) {}
  };

  return (
    <DrawerForm
      key="add_record_drawer_form"
      title="新建记录"
      drawerProps={{
        destroyOnClose: true,
        width: 1000,
        // onClose:()=>{
        //   console.log(selectSource);
        //   setSelectSourceState(undefined);
        // }
      }}
      formRef={formRef}
      trigger={<Button type="primary">新建记录</Button>}
      onOpenChange={(visible) => {
        if (visible) {
          loadSourceData();
          setSelectSourceState(undefined);
          loadOrganizationData();
        } else {
          setSelectSourceState(undefined);
          setCheckedOrganizationsState([]);
          setDataAttachmentState([]);
        }
      }}
      onFinish={async (values) => {
        console.log(values);
        if (scoreSymbols === 'add') {
        } else {
          values.score = -values.score;
        }
        if (values.publishTime !== undefined) {
          values.publishTime = values.publishTime + ' 00:00:00';
        }
        if (checkedOrganizations.length === 0) {
          message.warning('请选择联动单位');
          return false;
        }
        const response = await saveRecord({
          ...values,
          participateOrganizationIds: checkedOrganizations.map((item) => item.id),
          attachments: dataAttachment,
        });

        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
        }
        return true;
      }}
    >
      <Spin
        style={{
          textAlign: 'center',
        }}
        spinning={dataSource === undefined}
      >
        {dataSource !== undefined && (
          <>
            <ProFormCascader
              // width="xl"
              name="sourceIds"
              label="来源"
              rules={[{ required: true, message: '请选择来源' }]}
              fieldProps={{
                displayRender: (labels: string[], selectedOptions?: any[]) => {
                  return labels.map((label, i) => {
                    const option = selectedOptions[i];
                    if (i === labels.length - 1) {
                      return <span key={option.value}>{label}</span>;
                    }
                    return <span key={option.value}>{label} / </span>;
                  });
                },
                onChange: (values, selectedOptions) => {
                  if(selectedOptions) {
                    const option = selectedOptions[selectedOptions.length - 1];

                    if (option.value !== '7275100000020000') {
                      setSelectSourceState(option);
  
                      formRef.current?.setFieldsValue({
                        score: Math.abs(option.score),
                      });
                    } else {
                      /**
                       * 媒情网情社情转交办事项回复质效
                       */
                      setSelectSourceState(option);
  
                      formRef.current?.setFieldsValue({
                        score: 0,
                      });
                    }
  
                    if (option.score < 0) {
                      setScoreSymbolsState('minus');
                    } else {
                      setScoreSymbolsState('add');
                    }
  
                  }
                },
                options: dataSource,
              }}
            />
            {selectSource !== undefined && (
              <Typography>
                {selectSource?.score !== null && (
                  <Typography.Paragraph>
                    <blockquote>积分：{selectSource?.score}</blockquote>
                  </Typography.Paragraph>
                )}
                {selectSource?.describes !== null && (
                  <Typography.Paragraph>
                    <blockquote>备注：{selectSource?.describes}</blockquote>
                  </Typography.Paragraph>
                )}
              </Typography>
            )}
            <ProFormDigit
              width="xl"
              name="score"
              label="积分"
              min={0}
              max={1000}
              rules={[{ required: true, message: '请输入积分' }]}
              hidden={selectSource?.score === null && selectSource?.value !== '7275100000020000'}
              addonBefore={selectBefore}
              // fieldProps={{
              //   onChange: (values) => {
              //     console.log(scoreSymbols,values);
              //     if (scoreSymbols === 'add') {
              //       formRef.current?.setFieldsValue({
              //         score: values,
              //       });
              //     }
              //   }
              // }}
            />
            <ProFormText
              width="xl"
              name="title"
              label="标题"
              rules={[{ required: true, message: '请输入标题' }]}
              fieldProps={{
                allowClear: true,
                maxLength: 200,
              }}
            />
            <ProFormDatePicker
              width="md"
              name="publishTime"
              label="日期"
              rules={[{ required: true, message: '请输入日期' }]}
              fieldProps={{
                disabledDate,
                showToday: false,
              }}
            />
            <ProFormSelect
              name="participateOrganizationNames"
              label="联动单位"
              showSearch
              fieldProps={{
                mode: 'multiple',
                allowClear: true,
                showSearch: true,
                showArrow: false,
                open: false,
                optionFilterProp: 'children',
                filterOption: (input: any, option: any) => {
                  console.log(option);
                  // return option.options.filter((item: any) => item.label.includes(input));
                  return option.label.includes(input);
                },
                listHeight: 500,
                style: {
                  width: 488,
                },
              }}
              rules={[{ required: true, message: '请选择联动单位' }]}
              addonAfter={
                <DrawerForm
                  width="500px"
                  title="指派报送单位"
                  trigger={<a key="activeSaveJoin">点击添加</a>}
                  autoFocusFirstInput
                  drawerProps={{
                    destroyOnClose: true,
                  }}
                  onOpenChange={(visible: boolean) => {
                    if (visible) {
                      const checkNames = formRef.current?.getFieldValue(
                        'participateOrganizationNames',
                      ) as [];
                      if (checkNames) {
                        const checkOrgs = new Array();
                        checkedOrganizations?.forEach((item) => {
                          if (checkNames.includes(item?.name)) {
                            checkOrgs.push(item);
                          }
                        });
                        setCheckedOrganizationsState(checkOrgs);
                      }
                    }
                  }}
                  submitter={false}
                >
                  {treeOrganizationData && treeOrganizationData.length ? (
                    <Tree
                      defaultExpandAll
                      showLine={{ showLeafIcon: false }}
                      showIcon={true}
                      treeData={treeOrganizationData}
                      checkedKeys={checkedOrganizations.map((item) => {
                        return item.id;
                      })}
                      checkable
                      onCheck={(checkedKeys, e) => {
                        console.log('=======111111111=======');

                        const checkOrgs = new Array();

                        e.checkedNodesPositions?.forEach((item) => {
                          if (item.node?.item?.isFolder === 0) {
                            checkOrgs.push(item.node.item);
                          }
                        });

                        setCheckedOrganizationsState(checkOrgs);

                        formRef.current?.setFieldsValue({
                          participateOrganizationNames: Array.from(checkOrgs, ({ name }) => name),
                        });
                      }}
                    />
                  ) : (
                    <Empty />
                  )}
                </DrawerForm>
              }
            />

            <ProForm.Group>
              <ProFormTextArea
                width="xl"
                name="remarks"
                label="备注"
                fieldProps={{
                  allowClear: true,
                  rows: 3,
                  maxLength: 200,
                }}
              />
            </ProForm.Group>
            <Divider orientation="left" plain>
              添加证明
            </Divider>
            <div style={{ textAlign: 'right' }}>
              <Space align="center">
                <PlusOutlined />
                <AddAttachmentFile
                  onRefurbish={(attachments: PublicityRecordBo.Attachment[]) => {
                    setDataAttachmentState([...dataAttachment, ...attachments]);
                  }}
                />
                <AddAttachmentLink
                  onRefurbish={(attachment: PublicityRecordBo.Attachment) => {
                    setDataAttachmentState([...dataAttachment, attachment]);
                  }}
                />
                <AddAttachmentSignal
                  onRefurbish={(attachment: PublicityRecordBo.Attachment) => {
                    setDataAttachmentState([...dataAttachment, attachment]);
                  }}
                />
              </Space>
            </div>
            <ProList<PublicityRecordBo.Attachment>
              rowKey="id"
              ghost
              dataSource={dataAttachment}
              showActions="hover"
              metas={{
                title: {
                  dataIndex: 'name',
                  render: (text, row, index, action) => {
                    return (
                      <>
                        {row.type === 1 ? (
                          <Space size={0}>
                            <Tag color="blue">文件</Tag>
                          </Space>
                        ) : row.type === 2 ? (
                          <Tag color="green">链接</Tag>
                        ) : (
                          <Tag color="geekblue">口令</Tag>
                        )}
                        <span
                          style={{
                            fontWeight: 'bold',
                          }}
                        >
                          {row.name}
                        </span>
                      </>
                    );
                  },
                },
                description: {
                  render: (text, row, index, action) => {
                    return (
                      <Typography>
                        {selectSource?.score !== null && (
                          <Typography.Paragraph>
                            <blockquote>
                              {row.type === 1 ? (
                                <>
                                  {row.thumbUrl === '' ? (
                                    <Avatar shape="square" size={64} icon={<FileOutlined />} />
                                  ) : (
                                    <Avatar shape="square" size={64} src={row.thumbUrl} />
                                  )}
                                </>
                              ) : row.type === 2 ? (
                                row.link
                              ) : (
                                row.signal
                              )}
                            </blockquote>
                          </Typography.Paragraph>
                        )}
                      </Typography>
                    );
                  },
                },
              }}
            />
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};

export default AddRecord;
